<?php
namespace App\Http\Controllers;

use App\Models\Channel;
use App\Services\MiniAppService;
use App\Services\WechatService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Session;

class UsersController extends Controller
{
    /**
     * @param Channel $channel
     * @param Request $request
     * @throws \App\Exceptions\WechatException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function openid(Channel $channel, Request $request)
    {
        $wechatService = new WechatService($channel->mp_appid, $channel->mp_secret);
        $result = $wechatService->getAccessTokenByCode($request->input('code'));
        $callback = $request->input('callback');
        Session::put('openid_' . md5($channel->id), $result['openid']);
        return redirect($callback);
    }

    public function miniOpenid(Request $request)
    {
        $request->validate([
            'channel_id' => ['required', 'exists:channels,id'],
            'code' => ['required']
        ], [
            'channel_id.required' => '支付通道错误',
            'channel_id.exists' => '支付通道不存在',
            'code.required' => '获取信息失败'
        ]);
        $channelId = $request->input('channel_id');
        $code = $request->input('code');

        $channel = Channel::findOrFail($channelId);
        $miniAppService = new MiniAppService($channel->mini_appid, $channel->mini_secret);
        $result = $miniAppService->code2Session($code);
        return response()->json([
            'code' => 200,
            'message' => 'success',
            'data' => [
                'openid' => $result['openid']
            ]
        ]);
    }
}
